package controllers

import config.{MyAwait, MyRow, QTL}
import dao.{CmDao, CsDao, EpigDao, QtlDao}
import javax.inject.Inject
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}

import scala.concurrent.ExecutionContext

class ToolsController @Inject()(qtlDao: QtlDao, epigDao: EpigDao, cc: ControllerComponents)
                               (implicit exec: ExecutionContext) extends AbstractController(cc) with MyRow with MyAwait{

  def qtlPage = Action { implicit request =>
    Ok(views.html.tools.qtlPage())
  }

  def qtlInfoPage(id: Int) = Action.async { implicit request =>
    qtlDao.getById(id).map { x =>
      Ok(views.html.tools.qtlInfoPage(x))
    }
  }

  def getAllTrait = Action.async { implicit request =>
    qtlDao.getAll.map { x =>
      Ok(Json.toJson(x.map(_.`trait`).distinct))
    }
  }

  def qtlData(tr: String) = Action.async { implicit request =>
    qtlDao.getByTrait(tr).map { x =>
      val data = QTL.getQtlSvgData(x)
      Ok(Json.obj("qtlPlot" -> data, "qtlData" -> x.sortBy(_.left).map(_.getMapByT())))
    }
  }

  case class QtlData(epigType: String, repet: String, chr: String, start: Int, end: Int)

  val QtlForm = Form(
    mapping(
      "epigType" -> text,
      "repet" -> text,
      "chr" -> text,
      "start" -> number,
      "end" -> number
    )(QtlData.apply)(QtlData.unapply)
  )

  def getEpigInfosByRange = Action.async { implicit request =>
    val data = QtlForm.bindFromRequest.get
    val repet = "Cs" + data.repet.last
    epigDao.getByRange(data.start, data.end, data.epigType,"Chr" + data.chr,repet).map { x =>
      Ok(Json.toJson(x.map(_.getMapByT())))
    }
  }


}
